package com.chengzhi.eshopinventory.service.impl;

import com.chengzhi.eshopinventory.request.BaseRequest;
import com.chengzhi.eshopinventory.service.InventoryAsyncService;
import com.chengzhi.eshopinventory.thread.RequestThreadPool;
import org.springframework.stereotype.Service;

import java.util.concurrent.ArrayBlockingQueue;

/**
 * @description
 * @author: ruanchengzhi
 * @create: 2021-04-02 13:57
 **/
@Service
public class InventoryAsyncServiceImpl implements InventoryAsyncService {


    @Override
    public void precoss(BaseRequest request) {
        try {
            route(request.getInventoryId()).put(request);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }


    /**
     * 参考hashmap中hash算法
     *
     * @param inventoryId
     * @return java.util.concurrent.ArrayBlockingQueue<com.chengzhi.eshopinventory.request.BaseRequest>
     * @throws
     * @author ruanchengzhi
     * @date 2021/4/1
     */
    private ArrayBlockingQueue<BaseRequest> route(Long inventoryId) {
        RequestThreadPool threadPool = RequestThreadPool.getInstance();
        String key = String.valueOf(inventoryId);
        int h;
        int hashcode = (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
        int index = (threadPool.getSize() - 1) & hashcode;
        return threadPool.get(index);
    }
}
